using UnityEngine;
using System.Collections;

/// \class  gkSpawnTriggerByDistance
/// \brief  Make is owner spawn a random number of actor at regular scrolling distance
[AddComponentMenu("GK/Engine/Game/Spawn/gkSpawnTriggerByDistance")]
public class gkSpawnTriggerByDistance : gkSpawnTrigger 
{
	/// The minimum distance between spawn
	public float BetweenSpawnAverageDistance = 10.0f;
	
	/// The distance between spawn variation in percent
	public float DistanceVariationPercent;
	
	/// The scrolling info
	private gkScrollingInfo m_rScrollingInfo;
	
	/// The Current distance to wait between spawn
	private float m_fNextSpawnDistance;
	
	/// The last spawn distance from origin
	private Vector3 m_f3LastSpawnScrollingPosition;
	
	/// The scrolling movement since last spawn
	private Vector3 m_f3ScrollingMovementSinceLastSpawn;
	
	/// \brief  Called just after the game begin to play
    protected override void Start()
    {
		base.Start();
		
	    // Grab the scrolling info
	    m_rScrollingInfo = GameObject.Find("ScrollingInfo").GetComponent<gkScrollingInfo>();
    }
	
	/// \brief  Update the spawning process
	protected override void UpdateSpawn()
	{
		Vector3 f3CurrentScrollingPosition;
	
		// Compute the scrolling movement since last spawn
		f3CurrentScrollingPosition = m_rScrollingInfo.GetScrollingTotalMovement();
		m_f3ScrollingMovementSinceLastSpawn = f3CurrentScrollingPosition - m_f3LastSpawnScrollingPosition;
	
		base.UpdateSpawn();
	}
	
	/// \brief  Spawn the actors
	protected override void SpawnActors()
	{
		// Save the lst spawn position
		m_f3LastSpawnScrollingPosition = m_rScrollingInfo.GetScrollingTotalMovement();
	
		base.SpawnActors();
	
		// Select the next spawn distance to wait
		SelectNextSpawnDistance();
	}
	
	/// \brief  Select the next spawn distance to wait
	void SelectNextSpawnDistance()
	{
		float fRandomDistanceVariationPercent;
	
		// Apply random variation to have the distance of the next spawn
		fRandomDistanceVariationPercent = Random.Range(- DistanceVariationPercent, DistanceVariationPercent) ;
		m_fNextSpawnDistance = 
			BetweenSpawnAverageDistance + fRandomDistanceVariationPercent * BetweenSpawnAverageDistance;
	}
	
	/// \brief  Can we spawn again
	protected override bool CanSpawn()
	{
		return Mathf.Abs(m_f3ScrollingMovementSinceLastSpawn.x) > m_fNextSpawnDistance;
	}
}
